package com.android.interfata;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Vector;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

import android.net.ParseException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.menu.MenuAbout;
import com.android.menu.MenuContact;
import com.android.menu.MenuHelp;
import com.android.menu.MenuLegal;

import com.android.lazylist.LazyAdapterSearch;

public class SearchList extends Activity implements Runnable
{
	public String[] categories = { "", "", "", "", "Books", "Multimedia", "Music", "", "Movies", 
			"Electronics", "Computers", "Cameras", "Ebooks", "Software"};

	private String pozaDefault = "http://mail.pioneerinvestments.ro:333/images/img.jpg";
	
	
	ListView list;
    LazyAdapterSearch adapter;
	//LazyAdapter adapter;
    public int scrHeight, scrWidth;
    
    private ProgressDialog pd;
 	boolean primaData = true;
    
	
	public String[] title;
	public String[] detail;
	public String[] imgid; 
	public Double[] rating, price;
	public String[] authors, brand;
	public Long[] id;
	public String[] imageLarge;
	public String[] linkAmazon, linkEbay; 
	private int numResults;
	
	private String searchText;
	private int page = 0;
	
	
	/** Called when the activity is first created. */
	private static final String TAG = "Interfata 08";
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);		
		setContentView(R.layout.search_list);	
		

		/* username si logout din header - le completez cu datele corespunzatoare */
        TextView user = (TextView) findViewById(R.id.userHeader);
        SharedPreferences logPref = getSharedPreferences("LoginPref", MODE_PRIVATE);
    	String username = logPref.getString("user", "username");
    	user.setText(username);		
    	
        TextView logout = (TextView) findViewById(R.id.logoutHeader);
		/**** delogare ****/
		logout = (TextView) findViewById(R.id.logoutHeader);
		logout.setOnClickListener(new View.OnClickListener() 
		{
            public void onClick(View v) 
            {
            	askOK();
            }
        });
		/**** end delogare ****/
		
		  System.out.println("bbbbssssssssssss");
		Intent i = getIntent();
	    searchText = i.getStringExtra("searchText");
	    page = i.getIntExtra("page", 0);
	    
	    System.out.println("bbbbsss");
		
	    try
	    {
	    
		    tabHostAction();
		    searchBtnAction();
		    next_previous();
		 
		    //pd = ProgressDialog.show(this, "Working..", "Loading data", true, false);
			
			pd = new ProgressDialog(this);
			pd.setIndeterminate(true);
			pd.setIndeterminateDrawable(getResources().getDrawable(R.anim.loading_anim));
			pd.setMessage("Loading data. Please wait");
			//pd.setTitle("Cotrobaing...");
			pd.setCancelable(false);
			pd.show();
			
			Thread thread = new Thread(this);
			thread.start();
	    
	    }
	    catch(Exception e)
        {
        	 System.out.println(e + " " + e.getMessage() + " " + e.getCause());
        }
	}
	
	 @Override
    public void onResume()
    {
    	super.onResume();  //The activity is about to become visible.
		if (primaData == false)
		{
			/*
			Log.d("book", "resume" + primaData);
			pd = ProgressDialog.show(this, "Working..", "Loading data", true, false);
	
			Thread thread = new Thread(this);
			thread.start();
			*/
		}
		else
		{
			primaData = false;
		}
    }
	 
	 
	  
	    /* thread pentru acces la server */
	    public void run() 
	    {
	            //pi_string = Pi.computePi(800).toString()
	    	try 
			{
		    	getDataForList();
			} 
			catch (ParseException e) 
			{
				e.printStackTrace();
			}
	        
			handler.sendEmptyMessage(0);
	    }

	    private Handler handler = new Handler()
	    {
	            @Override
	            public void handleMessage(Message msg) 
	            {
	                pd.dismiss();
	                //tv.setText(pi_string);*/
	                try
	                {
	                	if (numResults == 0)
	                	{
	                		TextView NoItems = (TextView) findViewById(R.id.no_items_found);  
	    		        	NoItems.setVisibility(View.VISIBLE);
	                	}
	                	else
	                	{
		            		getSize();
		                	populare();
		                	showButtons();
	                	}
	                }
			    	catch( Exception e)
			    	{
			    		Log.d("err - handle populare", "err" + e.getLocalizedMessage());
			    	}
	            }
	    };
	    /* end thread pentru acces la server */
	    
	    
	    // populez lista
	    public void populare()
	    {
	    	try
	    	{
	    		
		        list=(ListView)findViewById(R.id.list);
		        adapter=new LazyAdapterSearch(this, imgid, title, detail, rating, price, imageLarge, 
		        		linkAmazon, linkEbay, id, authors, brand, scrHeight, scrWidth);
		        list.setAdapter(adapter);
		        
		    		/*
		    	list=(ListView)findViewById(R.id.list);
		        adapter=new LazyAdapter(this, imgid, title, detail, rating, price, imageLarge, 
		        		linkAmazon, linkEbay, id, authors, brand, scrHeight, scrWidth);
		        list.setAdapter(adapter);
		        */
		  	  	System.out.println("populare()");
	    		
	    	}
	    	catch(Exception e)
	    	{
	    		System.out.println("din populare() ");
	    	}
	    } 
	    
	
	

	
	
	
	
	/*              pentru popularea randurilor din listview              */

	
	private void initializari(int numResults)
	{
	    title = new String[numResults];
 		detail = new String[numResults];
 		imgid = new String[numResults]; 
		rating = new Double[numResults];
		price = new Double[numResults];
		brand = new String[numResults];
		authors = new String[numResults];
		id =  new Long[numResults];
		imageLarge = new String[numResults];
		linkAmazon = new String[numResults];
		linkEbay = new String[numResults];
			
		
	}
	
	private void next_previous()
	{
		System.out.println("In next_previous() inceput");
		
		TextView pagNum = (TextView) findViewById(R.id.page_number);
		pagNum.setText("Page:" + (page + 1));
		
		ImageView previous = (ImageView) findViewById(R.id.previous_page);
		
		previous.setOnClickListener(new View.OnClickListener()
        {				
			public void onClick(View v) 
			{
				Intent intent = new Intent(getApplicationContext(), SearchList.class);
				intent.putExtra("searchText", searchText);
				intent.putExtra("page", page - 1);
				startActivity(intent);		
				
			}
		});
		
		
		ImageView next = (ImageView) findViewById(R.id.next_page);
		
		next.setOnClickListener(new View.OnClickListener()
        {				
			public void onClick(View v) 
			{
				System.out.println("In next_previous() next");
				
				Intent intent = new Intent(getApplicationContext(), SearchList.class);
				intent.putExtra("searchText", searchText);
				intent.putExtra("page", page + 1);
				startActivity(intent);		
				
			}
		});
		
	}
	
	private void showButtons()
	{
		System.out.println("In showButtons()");
		
		TextView pageTV = (TextView)findViewById(R.id.page_number);
		pageTV.setVisibility(View.VISIBLE);
		
		
		ImageView previous = (ImageView) findViewById(R.id.previous_page);
		if ( page != 0)
		{
			previous.setVisibility(View.VISIBLE);
			
		}
		
		ImageView next = (ImageView) findViewById(R.id.next_page);
		if ( numResults == 10)
		{
			next.setVisibility(View.VISIBLE);
			
		}
		
	}
	
	
	public void getDataForList()
    {
    	try
    	{
    		//GetProdusByCategID3?CategID=string&pagina=string&intrariPagina=string&PretMinim=string&PretMaxim=string&ordonareTitlu=string&ordonarePret=string&ordonareAutor=string&ordonareBrand=string&NrOrdonari=string
	    	String xml = XMLfunctions.getXML("GetProdusByKeywords3?word=" + searchText + "&pagina="+ page +"&intrariPagina=10&PretMinim=0.0&PretMaxim=5000.0&category_id=0&ordonareTitlu=Deloc&ordonarePret=Deloc&ordonareAutor=Deloc&ordonareBrand=Deloc&ordonareCategorie=Deloc&NrOrdonari=0");
	    	
	    	System.out.println("getDataForList " + xml );
	        Document doc = XMLfunctions.XMLfromString(xml);
	        numResults = XMLfunctions.numResults(doc, "name");
	        
	        System.out.println("Nr de rezultate " + numResults);
	        
	        if (numResults != 0)
	        {
	        	 initializari(numResults);
	    			
	 	        
	 	        if((numResults <= 0))
	 	        {
	 	        	 	finish();
	 	        }
	 		          
	 	        NodeList nodes = doc.getElementsByTagName("TipProdus");
	 	        System.out.println(nodes.getLength());		
	 	        
	 			for (int i = 0; i < nodes.getLength(); i++)
	 			{							
	 								
	 				Element e = (Element)nodes.item(i);
	 				title[i] = XMLfunctions.getValue(e, "name");
	 				detail[i] = categories[Integer.parseInt(XMLfunctions.getValue(e, "categ_id"))];
	 							
	 				if (XMLfunctions.getValue(e, "imageSmall") == "")
	 					imgid[i] = pozaDefault;
	 				else
	 					imgid[i] = XMLfunctions.getValue(e, "imageSmall");
	 				
	 				rating[i] = Double.parseDouble(XMLfunctions.getValue(e, "Rating"));
	 				price[i] = Double.parseDouble(XMLfunctions.getValue(e, "Price"));
	 				
	 				id[i] =  Long.parseLong(XMLfunctions.getValue(e, "ID"));
	 				brand[i] =  XMLfunctions.getValue(e, "brand");
	 				authors[i] =  XMLfunctions.getValue(e, "authors");
	 				
	 				imageLarge[i] =  XMLfunctions.getValue(e, "imageLarge");
	 				
	 				//Linkuri catre ebay Amazon
	 				
	 				linkAmazon[i] =  XMLfunctions.getValue(e, "linkAmazon");
	 				linkEbay[i] =  XMLfunctions.getValue(e, "linkEbay");
	 				
	 			}	
	 		
	 			System.out.println(title.length + " " + title[0]);
	        	
	        }
	    
	        
	       
    	}
    	catch( Exception e)
    	{
    		System.out.println("Din getDataForList()" + e);
    	}
    }

 
	/*---------------------------------------------------------------------------------------*/
	
	 @Override
	    public void onDestroy()
	    {
	        list.setAdapter(null);
	        super.onDestroy();
	    }
	
	    
	    private void getSize ()
	    {
	    	// preiau dimensiunile ecranului
	 		Display display = getWindowManager().getDefaultDisplay(); 
			scrWidth = (int)display.getWidth();  // deprecated
			scrHeight = (int)display.getHeight(); 
	    }
	    
	    /*-----------------------------------------------------------------------------------------*/
	
	
	
	
	
	/*             end pentru popularea randurilor din listview              */
	
	
	
	/*     menu      */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	Intent intent;
        switch (item.getItemId()) 
        {
            case R.id.menu_about:     
            	intent = new Intent(getApplicationContext(), MenuAbout.class);
				startActivity(intent);
                break;
            case R.id.menu_help:     
            	intent = new Intent(getApplicationContext(), MenuHelp.class);
				startActivity(intent);
                break;
            case R.id.menu_legal: 
            	intent = new Intent(getApplicationContext(), MenuLegal.class);
				startActivity(intent);
            	break;
            case R.id.menu_contact:
            	intent = new Intent(getApplicationContext(), MenuContact.class);
				startActivity(intent);
            	break;
        }
        return true;
    }
	/*     end menu      */
    
    
	private void searchBtnAction ()
	{
		/*
		ImageView searchIV = (ImageView) findViewById(R.id.searchIV);
		searchIV.setOnClickListener(new View.OnClickListener()
        {
			public void onClick(View v) 
			{			
				EditText searchText = (EditText) findViewById(R.id.searchText); 
				String ST = searchText.getText().toString();
				ST = replace(ST, " ", "%20");
				
				Intent intent = new Intent(getApplicationContext(), SearchList.class);
				intent.putExtra("searchText", ST);
				startActivity(intent);
			}
        });
        */

		Button search = (Button) findViewById(R.id.searchBtn);
		search.setOnClickListener(new View.OnClickListener()
        {
			public void onClick(View v) 
			{			
				EditText searchText = (EditText) findViewById(R.id.searchText); 
				String ST = searchText.getText().toString();
				ST = replace(ST, " ", "%20");
				
				Intent intent = new Intent(getApplicationContext(), SearchList.class);
				intent.putExtra("searchText", ST);
				startActivity(intent);
			}
        });
	}
	

	static String replace(String str, String pattern, String replace)
	{
		String str1;
		int i = 0;
		while (i < str.length())
		{
			
			if ( str.charAt(i) == ' '  && str.charAt(i+1) == ' ')
			{
				str1 = str.substring(0, i) + str.substring(i + 2, str.length());
				str = str1;
			}
			else
				i++;
		}	
		
	    int s = 0;
	    int e = 0;
	    StringBuffer result = new StringBuffer();

	    while ((e = str.indexOf(pattern, s)) >= 0)
	    {
	        result.append(str.substring(s, e));
	        result.append(replace);
	        s = e+pattern.length();
	    }
	    result.append(str.substring(s));
	    return result.toString();
	}
	
	
	/*           tabHost fictiv - actiunile "butoanelor"          */
	private void tabHostAction()
	{
		
        ImageView img0 = (ImageView) findViewById(R.id.img0);
        ImageView img1 = (ImageView) findViewById(R.id.img1);
        ImageView img2 = (ImageView) findViewById(R.id.img2);
        TextView text0 = (TextView) findViewById(R.id.text0);
        TextView text1 = (TextView) findViewById(R.id.text1);
        TextView text2 = (TextView) findViewById(R.id.text2);
        
        img0.setOnClickListener(new View.OnClickListener()
        {
			
			public void onClick(View v) 
			{
				Intent intent = new Intent(getApplicationContext(), InterfActivity.class);
				intent.putExtra("activity", 0);
				intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION );
				startActivity(intent);
			}
		});
        text0.setOnClickListener(new View.OnClickListener()
        {
			
			public void onClick(View v) 
			{
				Intent intent = new Intent(getApplicationContext(), InterfActivity.class);
				intent.putExtra("activity", 0);
				intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION );
				startActivity(intent);
			}
		});
        
        img1.setOnClickListener(new View.OnClickListener()
        {
			
			public void onClick(View v) 
			{
				Intent intent = new Intent(getApplicationContext(), InterfActivity.class);
				intent.putExtra("activity", 1);
				intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION );
				startActivity(intent);
			}
		});
        text1.setOnClickListener(new View.OnClickListener()
        {
			
			public void onClick(View v) 
			{
				Intent intent = new Intent(getApplicationContext(), InterfActivity.class);
				intent.putExtra("activity", 1);
				intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION );
				startActivity(intent);
			}
		});
        
        img2.setOnClickListener(new View.OnClickListener()
        {
			
			public void onClick(View v) 
			{
				Intent intent = new Intent(getApplicationContext(), InterfActivity.class);
				intent.putExtra("activity", 2);
				intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION );
				startActivity(intent);
			}
		});
        text2.setOnClickListener(new View.OnClickListener()
        {
			
			public void onClick(View v) 
			{
				Intent intent = new Intent(getApplicationContext(), InterfActivity.class);
				intent.putExtra("activity", 2);
				intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION );
				startActivity(intent);
			}
		});

	}
    /*           end tabHost fictiv             */
	
	

	
	
	/**** delogare ****/
	private void askOK()
	{
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int which)
		    {
		        switch (which)
		        {
			        case DialogInterface.BUTTON_POSITIVE:
			        	delPref();
			        	gotoLogin();
			        	break;
	
			        case DialogInterface.BUTTON_NEGATIVE:
			            //No button clicked
			            break;
		        }
		    }
		};

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to logout?").setPositiveButton("Yes", dialogClickListener)
		    .setNegativeButton("No", dialogClickListener).show();
	}
	

	private void delPref ()
	{
    	// au nevoie de contextul aplicatiei deci nu le pot pune in clasa pentru delogare
    	SharedPreferences logPref = getSharedPreferences("LoginPref", MODE_PRIVATE);
    	SharedPreferences.Editor prefEditor = logPref.edit();
    	prefEditor.clear();
    	prefEditor.commit();
	}
	
	private void gotoLogin()
	{
		Intent intent = new Intent(getApplicationContext(), Login.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	
		finish();
	}
	/**** end delogare ****/
	
}